﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WXGSystem.ToolKit;

namespace WXGSystem.Web.Filters
{
    [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public class MvcErrorFilter : HandleErrorAttribute
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnException(ExceptionContext filterContext)
        {
            if (filterContext == null)
                base.OnException(filterContext);
            else
            {
                var request = (((System.Web.Mvc.ControllerContext)(filterContext)).RequestContext.HttpContext).Request;
                if (filterContext.Exception is HttpAntiForgeryException)
                {
                    filterContext.ExceptionHandled = true;
                    base.OnException(filterContext);
                    filterContext.Result = new RedirectResult(request.RawUrl);
                }
                else if (request.IsAjaxRequest())
                {
                    filterContext.ExceptionHandled = true;
                    var returnData = new { IsOK = false, Msg = "发生异常！" };
                    filterContext.Result = new JsonResult { Data = returnData };
                    LogHelper.Error(filterContext.Exception.ToString());
                }

            }
        }
    }
}